package main

import (
	"log"
)

// 流控
type ConnLimiter struct {
	concurrentConn int
	bucket         chan int
}

// 流控构造函数
func NewConnLimiter(cc int) *ConnLimiter {
	return &ConnLimiter{
		concurrentConn: cc,
		bucket:         make(chan int, cc),
	}
}

func (cl *ConnLimiter) GetConn() bool {
	if len(cl.bucket) >= cl.concurrentConn {
		log.Printf("too many connections, max is %d", cl.concurrentConn)
		return false
	}

	// 写一个1
	cl.bucket <- 1
	return true
}

func (cl *ConnLimiter) ReleaseConn() {
	// 读一个数
	c := <-cl.bucket
	log.Printf("release one connection, current connection: %d", c)
}
